package ch.elca.lol.puissance4.player;

import ch.elca.lol.puissance4.board.Board;
import ch.elca.lol.puissance4.game.Token;
import ch.elca.lol.puissance4.util.Util;

public class BasicAI extends PlayerHelper {
	
	@Override
	public int play(Board b) {
		int move;
		
		Iterable<Integer> possible = Util.possiblePlays(b);
		
		move = findWinningMove(b, possible);
		if(move != -1)
			return move;
		
		move = findLosingMove(b, possible);
		if(move != -1)
			return move;
		
		return heuristic(b, possible);
	}
	
	private int heuristic(Board b, Iterable<Integer> possible) {
		int col = -1;
		int val = Integer.MIN_VALUE;
		
		for(int x : possible) {
			int curVal = heuristicMove(b, x);
			if(curVal > val) {
				val = curVal;
				col = x;
			}
		}
		
		return col;
	}
	
	private int heuristicMove(Board b, int x) {
		int middle = b.getWidth() / 2;
		int posScore;
		if(x <= middle)
			posScore = x;
		else
			posScore = b.getWidth() - x - 1;
		
		int hScore = b.getColumnHeight(x) / 2;
		int rand = Util.random(-1, 2);
		
		return 2 * posScore - hScore + rand;
	}
	
	private int findWinningMove(Board b, Iterable<Integer> possible) {
		Token self = getToken();
		
		for(int x : possible) {
			if(b.play(x, self).hasWon(self))
				return x;
		}
		return -1;
	}
	
	private int findLosingMove(Board b, Iterable<Integer> possible) {
		Token other = getToken().next();
		
		for(int x : possible) {
			if(b.play(x, other).hasWon(other))
				return x;
		}
		return -1;
	}
	
}
